package info.nixbear.tgcms.admin.client.view;

import info.nixbear.tgcms.admin.client.activity.TemplatesActivity;
import info.nixbear.tgcms.admin.client.place.TemplatesPlace.TemplateEditPlace;
import info.nixbear.tgcms.admin.shared.request.TemplateProxy;

import java.util.List;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.web.bindery.requestfactory.shared.EntityProxyId;

public class TemplatesView extends Composite {

	private static TemplatesViewUiBinder uiBinder = GWT.create(TemplatesViewUiBinder.class);

	interface TemplatesViewUiBinder extends UiBinder<Widget, TemplatesView> { }
	
	TemplatesActivity templatesActivity;
	
	public void setTemplatesActivity(TemplatesActivity templatesActivity) {
		this.templatesActivity = templatesActivity;
	}

	ProvidesKey<TemplateProxy> keyProvider = new ProvidesKey<TemplateProxy>() {
		public EntityProxyId<TemplateProxy> getKey(TemplateProxy item) {
			return (item == null) ? null : item.stableId();
		}
	};

	@UiField(provided = true)
	final CellList<TemplateProxy> cellList = new CellList<TemplateProxy>(new TemplateCell(), keyProvider);//

	
	public TemplatesView() {
		initWidget(uiBinder.createAndBindUi(this));
		
		
		// Add a selection model using the same keyProvider.
		final SingleSelectionModel<TemplateProxy> selectionModel = 
			new SingleSelectionModel<TemplateProxy>(keyProvider);
		
		cellList.setSelectionModel(selectionModel);
		
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			public void onSelectionChange(SelectionChangeEvent event) {
				TemplateProxy selected = selectionModel.getSelectedObject();
				if (selected != null) {
					templatesActivity.goTo(new TemplateEditPlace(Long.toString(selected.getId()), selected));
					selectionModel.setSelected(selected, false);
				}
			}
		});

	}

	
	
	
	
	/**
	 * A custom {@link Cell} used to render a {@link Contact}.
	 */
	private static class TemplateCell extends AbstractCell<TemplateProxy> {
		@Override
		public void render(Context context, TemplateProxy template, SafeHtmlBuilder sb) {
			if (template != null) {
				sb.appendEscaped(template.getName());
			} else {
				sb.appendEscaped("null");
			}
		}
	}
	
	public void setTemplates(List<TemplateProxy> templates) {
		cellList.setRowCount(templates.size(), true);
		cellList.setRowData(0, templates);
	}


}
